const baseURL = 'http://127.0.0.1:8080'

// 请求拦截器
const request = (urlOrOptions, optionsOrNull = {}) => {
  return new Promise((resolve, reject) => {
    // 处理参数，支持对象形式和url+options形式
    let url;
    let options;
    
    if (typeof urlOrOptions === 'string') {
      // 原来的调用方式: request(url, options)
      url = urlOrOptions;
      options = optionsOrNull;
    } else if (typeof urlOrOptions === 'object') {
      // 新的调用方式: request({url, method, data})
      url = urlOrOptions.url;
      options = urlOrOptions;
    } else {
      reject(new Error('无效的请求参数'));
      return;
    }
    
    // 根据URL判断使用哪个token
    let token;
    if (url.includes('/admin/') || url.includes('/merchant/') || options.isMerchant) {
      // 商家相关的接口使用merchant_token
      token = wx.getStorageSync('merchant_token');
      console.log('使用商家token');
    } else {
      // 普通用户接口使用token
      token = wx.getStorageSync('token');
      console.log('使用用户token');
    }
    
    // 合并请求头
    const header = {
      'Content-Type': 'application/json',
      ...options.header
    }
    
    // 添加认证token
    if (token) {
      header['Authorization'] = `Bearer ${token}`
    } else {
      console.log('未找到认证token');
    }
    
    // 构建完整URL
    const fullUrl = url.startsWith('http') ? url : `${baseURL}${url}`
    
    // 记录请求信息
    console.log('Request:', {
      url: fullUrl,
      method: options.method || 'GET',
      data: options.data,
      header
    })
    
    // 发送请求
    wx.request({
      url: fullUrl,
      method: options.method || 'GET',
      data: options.data,
      header,
      success(res) {
        // 记录响应
        console.log('Response:', res)
        
        // 处理返回结果
        if (res.statusCode === 200) {
          // 服务器自定义的成功状态
          resolve(res.data)
        } else if (res.statusCode === 401) {
          // 未授权，可能是token过期
          wx.removeStorageSync('token')
          wx.removeStorageSync('userInfo')
          
          // 判断是否为商家接口
          if (url.includes('/admin/') || url.includes('/merchant/')) {
            wx.removeStorageSync('merchant_token')
            wx.removeStorageSync('merchantInfo')
            // 跳转到商家登录
            wx.redirectTo({
              url: '/pages/admin/login/login'
            })
          } else {
            // 跳转到用户登录
            wx.redirectTo({
              url: '/pages/login/login'
            })
          }
          
          reject(new Error('登录已过期，请重新登录'))
        } else {
          // 其他错误
          reject(new Error(res.data.message || `请求失败: ${res.statusCode}`))
        }
      },
      fail(error) {
        console.error('请求失败:', error)
        reject(new Error('网络请求失败，请检查网络连接'))
      }
    })
  })
}

// API方法
module.exports = {
  // 基础请求方法
  request,

  // 用户相关
  login(data) {
    return request('/api/users/login', {
      method: 'POST',
      data
    })
  },

  register(data) {
    return request('/api/users/register', {
      method: 'POST',
      data
    })
  },

  logout() {
    return new Promise((resolve) => {
      // 这里不发送请求到后端，只在前端处理登出
      console.log('执行登出操作')
      try {
        // 清除本地存储
        wx.removeStorageSync('userInfo')
        wx.removeStorageSync('token')
        resolve({ success: true, message: '登出成功' })
      } catch (error) {
        console.error('登出失败:', error)
        // 即使发生错误也返回成功，确保UI正确更新
        resolve({ success: true, message: '登出成功' })
      }
    })
  },

  merchantLogout() {
    return new Promise((resolve) => {
      console.log('执行商家登出操作')
      try {
        // 清除商家本地存储
        wx.removeStorageSync('merchantInfo')
        wx.removeStorageSync('merchant_token')
        resolve({ success: true, message: '登出成功' })
      } catch (error) {
        console.error('登出失败:', error)
        resolve({ success: true, message: '登出成功' })
      }
    })
  },

  getUserInfo() {
    return request('/api/users/current', {
      method: 'GET'
    })
  },

  updateUserInfo(data) {
    return request('/api/users/info', {
      method: 'PUT',
      data
    })
  },

  // 订单相关
  getOrders(status, params = {}) {
    const queryParams = {
      page: params.page || 0,
      size: params.size || 10,
      sort: 'createTime,desc'
    };

    // 如果 status 是 undefined 或 0，获取所有订单
    if (status === undefined || status === 0) {
      return request('/api/orders', {
        method: 'GET',
        data: queryParams
      });
    }
    
    // 根据状态获取订单
    return request(`/api/orders/status/${status}`, {
      method: 'GET',
      data: queryParams
    });
  },

  getOrder(orderNo) {
    return request(`/api/orders/${orderNo}`, {
      method: 'GET'
    })
  },

  createOrder(data) {
    return request('/api/orders', {
      method: 'POST',
      data
    })
  },

  payOrder(orderNo) {
    return request(`/api/customer/orders/${orderNo}/pay`, {
      method: 'POST'
    })
  },

  cancelOrder(orderNo) {
    return request(`/api/orders/${orderNo}/cancel`, {
      method: 'POST'
    })
  },

  confirmOrder(orderNo) {
    return request(`/api/orders/${orderNo}/confirm`, {
      method: 'POST'
    })
  },

  deleteCustomerOrder(orderNo) {
    return request(`/api/customer/orders/${orderNo}`, {
      method: 'DELETE'
    })
  },

  // 购物车相关
  getCart() {
    return request('/api/cart', {
      method: 'GET'
    })
  },

  addToCart(data) {
    console.log('添加到购物车:', data)
    return request('/api/cart', {
      method: 'POST',
      data
    })
  },

  updateCart(data) {
    return request('/api/cart', {
      method: 'PUT',
      data
    })
  },

  removeFromCart(cartItemId) {
    return request(`/api/cart/${cartItemId}`, {
      method: 'DELETE'
    })
  },

  clearCart() {
    return request('/api/cart', {
      method: 'DELETE'
    })
  },

  getCartCount() {
    return request('/api/cart/count', {
      method: 'GET'
    })
  },

  checkCartItems() {
    return request('/api/cart/check', {
      method: 'POST'
    })
  },

  // 地址相关
  getAddressList() {
    return request('/api/addresses', {
      method: 'GET'
    });
  },

  getAddress(id) {
    return request(`/api/addresses/${id}`, {
      method: 'GET'
    });
  },

  addAddress(data) {
    return request('/api/addresses', {
      method: 'POST',
      data
    });
  },

  updateAddress(id, data) {
    return request(`/api/addresses/${id}`, {
      method: 'PUT',
      data
    });
  },

  deleteAddress(id) {
    return request(`/api/addresses/${id}`, {
      method: 'DELETE'
    });
  },

  setDefaultAddress(id) {
    return request(`/api/addresses/${id}/default`, {
      method: 'PUT'
    });
  },

  getDefaultAddress() {
    return request('/api/addresses/default', {
      method: 'GET'
    });
  },

  // 管理员相关
  getAdminOverview() {
    return request('/api/admin/overview', {
      method: 'GET',
      isMerchant: true // 标记这是商家请求
    })
  },

  // 管理员订单相关
  getAdminOrders(params) {
    return request('/api/admin/orders', {
      method: 'GET',
      data: params
    })
  },

  getAdminOrder(orderNo) {
    return request(`/api/admin/orders/${orderNo}`, {
      method: 'GET'
    })
  },

  updateOrderStatus(orderNo, status) {
    return request(`/api/admin/orders/${orderNo}/status`, {
      method: 'PUT',
      data: { status }
    })
  },

  // 商品相关
  getProducts(params) {
    return request('/api/admin/products', {
      method: 'GET',
      data: {
        page: params.page - 1,
        size: params.size,
        keyword: params.keyword || ''
      }
    })
  },

  getCategories() {
    return request('/api/categories', {
      method: 'GET'
    })
  },

  initCategories() {
    return request('/api/categories/init', {
      method: 'POST'
    })
  },

  getProductsByCategory(categoryId, params) {
    return request(`/api/products/available/category/${categoryId}`, {
      method: 'GET',
      data: params
    })
  },

  getProductDetail(id) {
    return request(`/api/products/${id}`, {
      method: 'GET'
    })
  },

  getCarouselProducts() {
    return request('/api/products/carousel', {
      method: 'GET'
    })
  },

  getRecommendProducts(params) {
    return request('/api/products/recommend', {
      method: 'GET',
      data: params
    })
  },

  getHotProducts(params) {
    return request('/api/products/hot', {
      method: 'GET',
      data: params
    })
  },

  createProduct(data) {
    return request('/api/admin/products', {
      method: 'POST',
      data
    })
  },

  updateProduct(id, data) {
    return request(`/api/admin/products/${id}`, {
      method: 'PUT',
      data
    })
  },

  uploadImage: (filePath, isMerchant = false) => {
    return new Promise((resolve, reject) => {
      // 根据角色选择不同的上传端点
      const uploadUrl = isMerchant ? 
        '/api/merchant/upload/image' : 
        '/api/customer/upload/image';
      
      // 获取对应的token
      const token = isMerchant ? 
        wx.getStorageSync('merchant_token') : 
        wx.getStorageSync('token');
      
      if (!token) {
        reject(new Error('未登录，请先登录'));
        return;
      }

      wx.uploadFile({
        url: `${baseURL}${uploadUrl}`,
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success(res) {
          try {
            const data = JSON.parse(res.data);
            if (data.success) {
              resolve(data);
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } catch (error) {
            reject(new Error('解析响应失败'));
          }
        },
        fail(error) {
          reject(error);
        }
      });
    });
  },

  updateProductStatus(id, status) {
    return request(`/api/admin/products/${id}/status?status=${status}`, {
      method: 'PUT'
    })
  },

  updateProductDisplay(id, data) {
    return request(`/api/admin/products/${id}/display`, {
      method: 'PUT',
      data
    })
  },

  deleteProduct(id) {
    return request(`/api/admin/products/${id}`, {
      method: 'DELETE',
      header: {
        'Content-Type': 'application/json'
      }
    })
  },

  searchProducts(name, status = 1) {
    return request(`/api/products/search`, {
      method: 'GET',
      data: { name, status }
    })
  },

  // 评论相关
  getProductReviews(productId, params) {
    return request(`/api/reviews/products/${productId}`, {
      method: 'GET',
      data: params
    })
  },

  getUserReviews(userId, params) {
    return request(`/api/reviews/users/${userId}`, {
      method: 'GET',
      data: params
    })
  },

  createReview(productId, data, images) {
    const formData = new FormData()
    formData.append('review', JSON.stringify(data))
    if (images && images.length > 0) {
      images.forEach(image => {
        formData.append('images', image)
      })
    }
    return request(`/api/reviews/products/${productId}`, {
      method: 'POST',
      data: formData,
      header: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  updateReview(reviewId, data, images) {
    const formData = new FormData()
    formData.append('review', JSON.stringify(data))
    if (images && images.length > 0) {
      images.forEach(image => {
        formData.append('images', image)
      })
    }
    return request(`/api/reviews/${reviewId}`, {
      method: 'PUT',
      data: formData,
      header: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  deleteReview(reviewId) {
    return request(`/api/reviews/${reviewId}`, {
      method: 'DELETE'
    })
  },

  getReviewReplies(reviewId, params) {
    return request(`/api/reviews/${reviewId}/replies`, {
      method: 'GET',
      data: params
    })
  },

  createReply(reviewId, data) {
    return request(`/api/reviews/${reviewId}/replies`, {
      method: 'POST',
      data
    })
  },

  updateReply(replyId, data) {
    return request(`/api/reviews/replies/${replyId}`, {
      method: 'PUT',
      data
    })
  },

  deleteReply(replyId) {
    return request(`/api/reviews/replies/${replyId}`, {
      method: 'DELETE'
    })
  },

  likeReview(reviewId) {
    return request(`/api/reviews/${reviewId}/like`, {
      method: 'POST'
    })
  },

  unlikeReview(reviewId) {
    return request(`/api/reviews/${reviewId}/like`, {
      method: 'DELETE'
    })
  },

  likeReply(replyId) {
    return request(`/api/reviews/replies/${replyId}/like`, {
      method: 'POST'
    })
  },

  unlikeReply(replyId) {
    return request(`/api/reviews/replies/${replyId}/like`, {
      method: 'DELETE'
    })
  },

  // 获取订单详情
  getOrderDetail(orderNo) {
    return request(`/api/orders/${orderNo}`)
  },

  // 提交商品评价
  submitReview(data) {
    console.log('提交评价API调用:', data);
    const productId = data.productId;
    
    if (!productId) {
      console.error('评价缺少商品ID:', data);
      return Promise.reject(new Error('评价必须包含商品ID'));
    }
    
    // 尝试使用POST请求提交评价
    try {
      // 检查是否有图片URLs
      const hasImageUrls = data.imageUrls && Array.isArray(data.imageUrls) && data.imageUrls.length > 0;
      console.log(`评价是否包含图片: ${hasImageUrls}, 数量: ${hasImageUrls ? data.imageUrls.length : 0}`);
      
      // 记录完整的提交URL，方便调试
      const submitUrl = `/api/reviews/products/${productId}/json`;
      console.log(`提交评价到URL: ${submitUrl}`);
      
      // 确保imageUrls是一个数组，即使为空
      let imageUrls = [];
      
      // 严格检查imageUrls格式
      if (data.imageUrls) {
        if (Array.isArray(data.imageUrls)) {
          imageUrls = data.imageUrls;
        } else if (typeof data.imageUrls === 'string') {
          try {
            // 尝试解析JSON字符串
            imageUrls = JSON.parse(data.imageUrls);
          } catch (e) {
            // 如果解析失败，尝试按逗号分隔
            imageUrls = data.imageUrls.split(',').filter(url => url.trim() !== '');
          }
        }
      }
      
      // 确保imageUrls是数组格式
      if (!Array.isArray(imageUrls)) {
        console.error('imageUrls格式不正确，设置为空数组', imageUrls);
        imageUrls = [];
      }
      
      // 过滤掉无效的URL
      imageUrls = imageUrls.filter(url => url && typeof url === 'string' && url.trim() !== '');
      console.log('处理后的imageUrls:', imageUrls);
      
      // 构建提交数据，不使用FormData
      const submitData = {
        content: data.content,
        rating: data.rating,
        orderNo: data.orderNo,
        imageUrls: imageUrls
      };
      
      // 记录最终提交的数据
      console.log('最终提交的评价数据:', JSON.stringify(submitData));
      
      // 使用JSON格式直接提交
      return request(submitUrl, {
        method: 'POST',
        data: submitData,
        header: {
          'Content-Type': 'application/json'
        }
      }).then(response => {
        // 记录响应结果，帮助调试
        console.log('评价提交响应:', response);
        if (response.success) {
          console.log('评价提交成功');
        } else {
          console.error('评价提交失败:', response.message);
        }
        return response;
      }).catch(error => {
        // 详细记录错误
        console.error('评价提交错误:', error);
        // 对特定错误进行友好处理
        if (error.message && error.message.includes('不能重复评价')) {
          return {
            success: false,
            message: '您已经评价过此订单，不能重复评价',
            code: 'ALREADY_REVIEWED'
          };
        }
        throw error; // 其他错误继续向上抛出
      });
    } catch (error) {
      console.error('评价提交过程出错:', error);
      return Promise.reject(error);
    }
  },
  
  // 新增 - 获取上传URL
  getUploadUrl() {
    return `${baseURL}/api/upload/image`
  },

  // 客户订单相关
  getCustomerOrders(status, params = {}) {
    const queryParams = {
      page: params.page || 0,
      size: params.size || 10,
      sort: 'createTime,desc'
    };

    // 如果 status 是 undefined 或 0，获取所有订单
    if (status === undefined || status === 0) {
      return request('/api/customer/orders', {
        method: 'GET',
        data: queryParams
      });
    }
    
    // 根据状态获取订单
    return request(`/api/customer/orders/status/${status}`, {
      method: 'GET',
      data: queryParams
    });
  },

  getCustomerOrder(orderNo) {
    return request(`/api/customer/orders/${orderNo}`, {
      method: 'GET'
    })
  },

  // 获取订单详情（兼容性函数）
  getCustomerOrderDetail(orderNo) {
    return this.getCustomerOrder(orderNo);
  },

  createCustomerOrder(data) {
    return request('/api/customer/orders', {
      method: 'POST',
      data
    })
  },

  payCustomerOrder(orderNo) {
    return request(`/api/customer/orders/${orderNo}/pay`, {
      method: 'POST'
    })
  },

  cancelCustomerOrder(orderNo) {
    return request(`/api/customer/orders/${orderNo}/cancel`, {
      method: 'POST'
    })
  },

  confirmCustomerOrder(orderNo) {
    return request(`/api/customer/orders/${orderNo}/confirm`, {
      method: 'POST'
    })
  },

  // 商家订单相关
  getMerchantOrders(params = {}) {
    return request('/api/merchant/orders', {
      method: 'GET',
      data: params,
      isMerchant: true
    });
  },

  getMerchantOrder(orderNo) {
    return request(`/api/merchant/orders/${orderNo}`, {
      method: 'GET',
      isMerchant: true
    });
  },

  updateMerchantOrderStatus(orderNo, status, notes) {
    return request(`/api/merchant/orders/${orderNo}/status?status=${status}${notes ? `&processingNotes=${notes}` : ''}`, {
      method: 'PUT',
      isMerchant: true
    });
  },
  
  deleteMerchantOrder(orderNo) {
    return request(`/api/merchant/orders/${orderNo}`, {
      method: 'DELETE',
      isMerchant: true
    })
  },

  // 从购物车中移除特定商品ID的商品
  removeItemsFromCart(productIds) {
    if (!Array.isArray(productIds) || productIds.length === 0) {
      return Promise.resolve({ success: true, message: '没有需要移除的商品' });
    }
    return this.request({
      url: '/api/cart/removeItems',
      method: 'DELETE',
      data: productIds
    });
  },

  // 导出getBaseUrl方法
  getBaseUrl() {
    return baseURL;
  }
}
